package com.cty.Stack;

public class calculator02 {
    public static void main(String[] args) {
        //写一个表达式
        String expression = "70+189-2";
        //创建一个索引
        int index = 0;
        //创建两个栈
        ArrayStack2 numStack = new ArrayStack2(20);//数栈
        ArrayStack2 operStack = new ArrayStack2(20);//符号栈
        //创建两个数字用于接收栈中pop出的数字
        int num1;
        int num2;
        //创建一个字符用于接受栈中的运算符
        int oper;
        char ch;
        int res;
        //考虑一下多位数的问题
        String keepNum = "";
        while (true) {
            ch = expression.substring(index,index+1).charAt(0);
            if (operStack.isOper(ch)) {
                if (!operStack.isEmpty()) {
                    if (operStack.oper(ch) <= operStack.oper(operStack.peek())) {
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        oper = operStack.pop();
                        res = operStack.cal(num1,num2,oper);
                        numStack.push(res);
                        operStack.push(ch);
                    } else {
                        operStack.push(ch);
                    }
                } else {
                    operStack.push(ch);
                }
            } else {
                if (index == expression.length() -1) {
                    numStack.push(ch -48);
                } else {
                    keepNum += ch;
                    while (true) {
                        ch = expression.substring(index+1,index+2).charAt(0);
                        if (operStack.isOper(ch)) {
                            numStack.push(Integer.parseInt(keepNum));
                            break;
                        }
                        keepNum += ch;
                        index++;
                    }
                    keepNum = "";
                }
            }
            index++;
            if (index >= expression.length()) {
                break;
            }
        }
        while (!operStack.isEmpty()) {
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            res = operStack.cal(num1,num2,oper);
            numStack.push(res);
        }
        res = numStack.pop();
        System.out.printf("表达式%s的结果是:%d",expression,res);
    }
}
